from django.shortcuts import render
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
import random
from django_redis import get_redis_connection

from verifications import constants
from meiduo_mall.libs.yuntongxun.sms import CCP

# Create your views here.

#获取日志器
import logging
logger = logging.getLogger('django')

#GET /sms_codes/(?P<mobile>1[3-9]\d{9})/

class SMSCodeView(APIView):
    def get(self,request,mobile):
        '''
        获取短信验证码：
        1.随机生成6位数字作为短信验证码
        2.在redis中存储短信验key功
        '''
        #判断给mobile　60s之内是否发送过短信
        redis_conn = get_redis_connection('verify_codes')

        send_flag = redis_conn.get('send_flag_%s' % mobile) #None

        if send_flag:
            #60s之内给mobile　发送过短信
            return Response({'message':'发送短信过于频繁'},status=status.HTTP_403_FORBIDDEN)



        # 1.随机生成6位数字作为短信验证码
        sms_code = '%06d' % random.randint(0,999999)
        logger.info('短信验证码为：%s' % sms_code)

        # 2.在redis中存储短信验证内容,以sms_mobile为key,以验证码内容为value


        # redis_conn.set('key','value','expires')
        # redis_conn.setex('key','expires','value')


        #创建redis管道对象
        pl = redis_conn.pipeline()

        # 向redis管道中添加命令
        pl.setex('sms_%s' % mobile,constants.SMS_CODE_REDIS_EXPIRES,sms_code)
        pl.setex('send_flag_%s' % mobile,constants.SEND_SMS_CODE_INTERVAL,1)

        #一次性执行管道中的所有命令
        pl.execute()

        # 3.使用运通讯给mobile发送短信
        expires = constants.SMS_CODE_REDIS_EXPIRES // 60

        #发出发送短息任务消息
        from celery_tasks.sms.tasks import  send_sms_code
        send_sms_code.delay(mobile,sms_code,expires)


        # 4.返回应答,短信发送成功
        return Response({'message':'OK'})